//
//  HotDetailsViewController.m
//  SugarPile
//
//  Created by Charlie. on 16/1/21.
//  Copyright © 2016年 www.lanou39.蓝鸥科技. All rights reserved.
//

#import "HotDetailsViewController.h"
#import "LCPrefixHeader.pch"
#import "HotDetailsTableViewCell.h"
#import "DvdCollectionViewCell.h"
#import "SpecialViewController.h"
#import "UserViewController.h"
#import "CDViewController.h"
#import "HotDetailsModel.h"

#import "DataBaseManager.h"
#import "Movie.h"
#import "History.h"
#import <UMSocial.h>
@interface HotDetailsViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, PassDelegte, UMSocialUIDelegate>
@property (nonatomic, retain) NSMutableArray *dvdArr; /**< 解析点赞的人数*/
@property (nonatomic, retain) UITableView *detailTableView;/**<详情页tabelView*/
@property (nonatomic, retain) NSDictionary *dataDic; /**<所有数据*/
@property (nonatomic, assign) CGFloat f; /**<记录高度*/
@property (nonatomic, retain) UIView *footerView; /**<脚高背景*/
@property (nonatomic, retain) UICollectionView *dvdCollection; /**<专辑collection*/
@property (nonatomic, retain) NSMutableArray *arr; /**< 保存的model */
@end

@implementation HotDetailsViewController

-(void)dealloc
{
    [_detailsId release];
    [_detailTableView release];
    [_dvdArr release];
    [_dvdCollection release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor blueViolet];
    //    NSLog(@"%@", _detailsId.stringValue);
//
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(fanhui)];
#pragma mark - 按钮
     [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];//导航条返回键带的首页 让他消失
//    UIBarButtonItem *back =  self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(xiangqing)] autorelease];
//    UIBarButtonItem *detail = self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"详情" style:UIBarButtonItemStylePlain target:self action:nil] autorelease];
//    self.navigationItem.leftBarButtonItems = @[back, detail];

    // 数据解析
    [self dataHandle];
    
    // 记录历史 当push到当前页面的时候 记录本页数据到数据库
    // 延时一秒执行记录历史方法


    

    
    UIBarButtonItem *item1  = self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(right)] autorelease];
    UIBarButtonItem *item2 = self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(shouchang)] autorelease];
    self.navigationItem.rightBarButtonItems = @[item1, item2];
    
    
    // 创建TableView
    [self createTableView];
    // 创建脚高
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 0, HEIGHT / 4 + 20)];
    footer.backgroundColor = [UIColor whiteColor];
    _detailTableView.tableFooterView = footer;
    [footer release];
    // 创建脚高背景
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, WIDTH - 20, HEIGHT / 4)];
    _footerView.backgroundColor = [UIColor floralWhite];
    [footer addSubview:_footerView];
    
    // 创建Collection
    [self createCollection];
    
    
    

}
- (void)record1
{
//    // 创建单例对象
//    DataBaseManager *dbManger = [DataBaseManager shareInstance];
//    [dbManger openDB2];
//    // 创建表
//    [[DataBaseManager shareInstance] HistoryTabel];
    
    // 查询表
    NSMutableArray *arr1 = [[DataBaseManager shareInstance] Historyselect];
    if (arr1) {
        for (History *model in arr1) {
            if ([model.pubdate isEqualToString:_detailsId.stringValue]) {
                //创建
                NSLog(@"已经记录历史 ");
                return;
            }
        }
        
    }
    // 创建数据库类
    History *m = [[History alloc] init];
    // 把需要放入数据库的数据防区数据库
    // 主文本
    m.movieName = _dataDic[@"data"][@"msg"];
    NSLog(@"记录历史成功");
    // Id
    m.pubdate = _detailsId.stringValue;
    // 调用数据库方法
    [[DataBaseManager shareInstance] insertHistory:m];

    }
- (void)shouchang
{
//    // 创建单例对象
//    DataBaseManager *dbManger = [DataBaseManager shareInstance];
//    [dbManger openDB];
//    // 创建表
//    [[DataBaseManager shareInstance] createTabel];
    
    // 查询表
    NSMutableArray *arr1 = [[DataBaseManager shareInstance] select];
    if (arr1) {
        
        for (Movie *model in arr1) {
            if ([model.pubdate isEqualToString:_detailsId.stringValue]) {
                //创建
                UIAlertController *al = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经收藏" preferredStyle:UIAlertControllerStyleAlert];
                //显示
                [self presentViewController:al animated:YES completion:^{
                    // 一秒后执行diss方法
                    [self performSelector:@selector(diss:) withObject:self afterDelay:1];

                }];
                NSLog(@"已经收藏 ");
                return;
            }
        }
        
    }
    // 创建数据库类
    Movie *m = [[Movie alloc] init];
    // 把需要放入数据库的数据防区数据库
    // 主文本
    m.movieName = _dataDic[@"data"][@"msg"];
    // Id
    m.pubdate = _detailsId.stringValue;
    // 调用数据库方法
    [[DataBaseManager shareInstance] insertMovie:m];
    //创建
    UIAlertController *al = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
    //显示
    [self presentViewController:al animated:YES completion:^{
        // 一秒后执行diss 方法
        [self performSelector:@selector(diss:) withObject:self afterDelay:1];

    }];
    
}
// 延时程序 将提示取消
- (void)diss:(id)a
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
    
}
- (void)right
{
   
    NSString *str = [_dataDic[@"data"][@"photo"][@"path"] stringByReplacingOccurrencesOfString:@"_webp" withString:@""];
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56a877c267e58e85140031d2"
                                      shareText:str
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,nil]
                                       delegate:self];
    
}

- (void)createCollection
{
    // 专辑名称
    UILabel *dvdLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, (WIDTH - 60) / 2, 44)];
    dvdLabel.text = @"收集到以下专辑";
//    dvdLabel.backgroundColor = [UIColor lightGreen];
    [self.footerView addSubview:dvdLabel];
    [dvdLabel release];
    // 线
    UIView *dvdView = [[UIView alloc] initWithFrame:CGRectMake(20, 9 + dvdLabel.frame.size.height, WIDTH - 60, 1)];
    dvdView.backgroundColor = [UIColor lightGrayColor];
    [self.footerView addSubview:dvdView];
    
    // 创建layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    // 设置layout方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 设置layout格式
    layout.itemSize = CGSizeMake(80, 80);
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    // 创建collection
   self.dvdCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(20, 15 + dvdLabel.frame.size.height, WIDTH - 40, 100) collectionViewLayout:layout];
    _dvdCollection.backgroundColor = [UIColor floralWhite];
    _dvdCollection.delegate = self;
    _dvdCollection.dataSource = self;
    _dvdCollection.showsHorizontalScrollIndicator = NO;
    [self.footerView addSubview:_dvdCollection];
    [_dvdCollection registerClass:[DvdCollectionViewCell class] forCellWithReuseIdentifier:@"dvdcell"];
    [_dvdCollection release];
    [layout release];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dvdArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DvdCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dvdcell" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor floralWhite];
    // 图片赋值
    NSString *str = [_dvdArr[indexPath.item][@"covers"] firstObject];
    [cell.dvdImage sd_setImageWithURL:[NSURL URLWithString:str]];
    return cell;
}
// collection点击方法
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    // push
    CDViewController *cdVC = [[CDViewController alloc] init];
    HotDetailsModel *m = _arr[indexPath.item];
    
    NSString *url = @"http://203.80.144.212/napi/album/detail/?include_fields=share_links_2%2Ccovers%2Cmembers%2Cmember_count%2Cmanagers&platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=69&album_id=76646519&platform_name=Android&locale=zh&app_code=nayutas";
    [LCAFNetWorking GETWithURL:[url stringByReplacingOccurrencesOfString:@"76646519" withString:[NSString stringWithFormat:@"%@", m.userId]]  completion:^(id result) {
        // 处理好的专辑头字典传入第二页
        cdVC.dataDic = result[@"data"];
        // 传入ID
        cdVC.ID = m.userId;
        cdVC.cdCount = m.count;

        [self.navigationController pushViewController:cdVC animated:YES];
    }];

}
//// 返回跳转
//- (void)xiangqing
//{
//    [self.navigationController popToRootViewControllerAnimated:YES];
//}
// 创建TableView
- (void)createTableView
{
    self.detailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    _detailTableView.delegate = self;
    _detailTableView.dataSource = self;
    [self.view addSubview:_detailTableView];
    [_detailTableView registerClass:[HotDetailsTableViewCell class] forCellReuseIdentifier:@"cell"];
    [_detailTableView release];
}
-(void)dataHandle
{
    NSString *url = @"http://203.80.144.213/napi/blog/detail/?include_fields=share_links_2%2Ctags%2Crelated_albums%2Crelated_albums.covers%2Ctop_like_users%2Ctop_comments%2Cextra_html&platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522704816%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=67&platform_name=Android&locale=zh&blog_id=512946535&app_code=nayutas";
    [LCAFNetWorking GETWithURL:[url stringByReplacingOccurrencesOfString:@"512946535" withString:_detailsId.stringValue]  completion:^(id result) {
        self.dataDic = result;
        self.dvdArr = result[@"data"][@"related_albums"];
        NSLog(@"!!!%@", [url stringByReplacingOccurrencesOfString:@"512946535" withString:_detailsId.stringValue]);
        
        self.arr = [HotDetailsModel modelHanderWithArray:result[@"data"][@"related_albums"]];
//        NSLog(@"%@", _dvdArr);
        // 刷新
        [_dvdCollection reloadData];
        [_detailTableView reloadData];
    }];

}
#pragma mark - tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HotDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    // 把data下数据传入cell
    cell.dataDic = _dataDic[@"data"];
    //cell不能被点击
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
    // 传值协议
    cell.delegte = self;
    
    
//    _userNameLabel.text = _dataDic[@"data"][@"sender"][@"username"];
    // 记录cell高度 三个底面的高度
    self.f = cell.dierView.frame.size.height + cell.godView.frame.size.height + cell.comView.frame.size.height;

//    cell.textLabel.text = @"大鹏起兮云飞扬";
    return cell;
}
#pragma mark - 实现cell评论更多id传值
-(void)chuanWithNumber:(NSNumber *)number
{
    SpecialViewController *specVC = [[[SpecialViewController alloc] init] autorelease];
    specVC.reply_id = number;
    [self.navigationController pushViewController:specVC animated:YES];
}
#pragma mark - 实现cell用户传值
- (void)userWithNumber:(NSNumber *)number
{
    
    UserViewController *userVC = [[[UserViewController alloc] init] autorelease];
    
    
    NSString *url = @"http://203.80.144.213/napi/people/profile/?include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&platform_version=4.4.4&device_platform=HM%2B2A&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=69&_ts=1456832673350&platform_name=Android&locale=zh&app_code=nayutas&user_id=6645294";
    [LCAFNetWorking GETWithURL:[url stringByReplacingOccurrencesOfString:@"6645294" withString:[NSString stringWithFormat:@"%@", number]]  completion:^(id result) {
        // 处理好的专辑头字典传入第二页
        userVC.user_id = number;
        userVC.dic = result[@"data"];
        // 跳转
        [self.navigationController pushViewController:userVC animated:YES];
    
    }];

    
}
// tableView点击
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return _f + 60;
}

// 视图已经出现
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self performSelector:@selector(record1) withObject:self afterDelay:0.1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
